package com.cn.nullframe.controllor;

import com.cn.nullframe.pojo.User;
import com.cn.nullframe.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * restful接口测试
 * url:http://localhost:8080/nullframe/rest/user
 */
@RequestMapping("testRest")
@Controller
public class TestRestfulController {

    @Autowired
    private UserService userService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 数据请求
     * http://localhost:8081/nullframe/rest/testRest/1/123
     *
     * @return
     */
    @RequestMapping(value = "{userId}/{id}", method = RequestMethod.GET)
    public ResponseEntity<User> queryOne(@PathVariable("userId") Long userId, @PathVariable("id") Long id) {
        try {
            User user = new User();
            user.setId(userId);
            User userResult = this.userService.queryOne(user);
            return ResponseEntity.ok(userResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    /**
     * http://localhost:8081/nullframe/rest/testRest
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<User> queryOne(User user) {
        try {
            userService.saveSelective(user);
            return ResponseEntity.status(HttpStatus.CREATED).body(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    /**
     * http://localhost:8081/nullframe/rest/testRest
     */
    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<Void> updateUser(User user) {
        try {
            this.userService.updateSelective(user);
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    /**
     * http://localhost:8081/nullframe/rest/testRest
     */
    @RequestMapping(method = RequestMethod.DELETE)
    public ResponseEntity<Void> delete(User user) {
        try {
            this.userService.deleteById(user.getId());
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

}
